#!/bin/sh
DEVICE='00:25:47:09:95:67'	#The mac address of the bluetooth device
BOUNDS=-15	#Setting the limiting Boundary Condition
DELAY=2.5	#Setting the refresh time, as Bluetooth can't handle so many connection at the same time
CONNECTED=0	#Default value for connected
PID=0		#Default value for process ID
PROCESS='xscreensaver'
START_ACTION='/usr/bin/xscreensaver -nosplash'	#The action which is to be run in background that shall trigger IN/OUT ACTIONS
OUT_ACTION='/usr/bin/xscreensaver-command -lock'	#The out action is that to lock the screensaver which is running in the background
IN_ACTION='/usr/bin/killall xscreensaver'	#The in action is to kill the locked screensaver which is running as well as the background START_ACTION
chmod +s /usr/bin/hcitool 2>/dev/null	#If signed in as root, to run the hcitool script as a normal user.
function checkcon
{
	num=$(hcitool con |grep $DEVICE -c)	#Filtering $DEVICE from the Active connections and counting the lines returned
	if [ $num == 1 ]; then	#If a connection exists to that device.
		CONNECTED=1
	elif [ -z "`hcitool cc $DEVICE 2>&1 sed 's/Scanning/d'`" ]; then	#if Connection to that device is successful.
		CONNECTED=1
	fi
	while [ $CONNECTED -ne 1 ]; do	#Looping and calling checkcon, till connection is established, can be other return value incase connection fails
		checkcon
done
}
function checkprocess
{
	PID=`ps -C $PROCESS --no-heading | awk '{ print $1 }'`	#To store the process ID of $PROCESS which is running in the background.
	if [ "$PID" == "" ];  then	#When the $PROCESS isn't running
	$START_ACTION &	>/dev/null 2>&1 #Start the process
	fi
}
echo "Proximity Detector"
checkcon	#Calling the checkcon function
state="IN"	#Declaring a variable state to see the current state of the mobile device.PURPOSE: To trigger only on change of state
while /bin/true; do
	checkcon
	checkprocess
	if [ $CONNECTED == 1 ]; then
        	signal=$(hcitool rssi $DEVICE |awk '{print int($4)}')
		if [ $signal -gt $BOUNDS ]; then	#both are negative values
			#echo "HERE"	#can also execute an action
			if [ "$state" == "OUT" ]; then	#Device is coming IN from OUT
				state="IN"
				$IN_ACTION >/dev/null 2>&1	#Kills the OUT_ACTION and START_ACTION
				$START_ACTION & >/dev/null 2>&1	#Restarting the Background Process
			fi

		else
			#echo "OUT"	#can also execute an action
			if [ "$state" == "IN" ]; then	#Device is going OUT from IN
				state="OUT"
				$OUT_ACTION >/dev/null 2>&1
			fi
		fi
	fi
	sleep $DELAY
done
